package fun.xinnix.websocket.service;

import fun.xinnix.websocket.domain.Constant;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 通道组池，管理所有websocket连接
 */
@Component
public class ChannelHandlerPool {
    public ChannelHandlerPool() {
    }

    public static Set<Channel> channelGroup = Collections.synchronizedSet(new HashSet<>());


    /**
     * 根据用户id查找channel
     */
    public static List<Channel> getChannelByUserId(String userId) {
        AttributeKey<String> key = AttributeKey.valueOf(Constant.WEBSOCKET_ATTRIBUTEKEY_USER);
        return ChannelHandlerPool.channelGroup.stream().filter(channel -> channel.attr(key).get().equals(userId))
                .collect(Collectors.toList());
    }

    /**
     * 根据channel 返回用户id
     */
    public static String getUserIdByChannel(Channel channel) {
        AttributeKey<String> key = AttributeKey.valueOf(Constant.WEBSOCKET_ATTRIBUTEKEY_USER);
        List<Channel> filterList = ChannelHandlerPool.channelGroup.stream().filter(item -> item.id().asLongText().equals(channel.id().asLongText())).collect(Collectors.toList());
        if (filterList.size() > 0) {
            return filterList.get(0).attr(key).get();
        }
        return "";

    }
}
